/**
 * @description  费用维护
 * @author shenhong
 */
import React, { PureComponent, Fragment } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { message, Popconfirm, Tooltip } from 'antd';
import { connect } from 'dva';
import { ContentPackage, TableC, AdvancedSearch, PrimaryC, DATA_ENTRY } from '../../../comps';
import costValue from '../../../utils/enumeratedValues/costValue';
import config from '../../../comps/business/tradingMarket/config';
import AddCost from './addCost';
import style from './index.less';

class CostMaintain extends PureComponent {
  constructor() {
    super();
    this.state = {
      tenantAdmin: false, // 是否为租户管理员
      superMan: false, // 是否为超户
      showEdit: false, //是否展示新增、编辑页面
      exchangecode: '', //交易平台
      currentPage: 1, //页码
      numInPage: 20, //每页条数
      columns: [],
      dataSource: [],
      classification: undefined, //查询条件--费用分类
      groupid: undefined, //查询条件--产品组
      productid: undefined, //查询条件--产品
      portfolioid: undefined, //查询条件--组合
      exchangecode: undefined, //查询条件--交易市场
      costtype: undefined, //查询条件--费用类型
      sectype: undefined, //查询条件--证券类别
      reset: false, //查询条件是否重置
    };
  }

  componentDidMount() {
    this.setState({
      tenantAdmin: localStorage.getItem('antd-pro-admin') == 'true',
      superMan: localStorage.getItem('antd-pro-superMan') == 'true',
    });
    this.handleSearch();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  //产品组select变化
  productGroupChange = (e) => {
    console.log(e);
  };

  //产品select变化
  productChange = (e) => {
    console.log(e);
  };

  //组合select变化
  portfolioidChange = (e) => {
    console.log(e);
  };

  //查询条件
  renderForm = () => {
    const { exchangecode } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'groupid',
          title: '产品组',
          type: DATA_ENTRY.PRODUCTGROUP,
          onRef: (ref) => this.setState({ productGroup: ref }),
          onChange: this.productGroupChange,
        },
        {
          dataIndex: 'productid',
          title: '产品',
          type: DATA_ENTRY.PRODUCTLIST,
          onRef: (ref) => this.setState({ product: ref }),
          onChange: this.productChange,
        },
        {
          title: '组合',
          type: DATA_ENTRY.PRODUCTGROUPTREE,
          onRef: (ref) => this.setState({ portfolioid: ref }),
          onChange: this.portfolioidChange,
          dataIndex: 'portfolioid',
          multiple: false,
        },
        {
          dataIndex: 'classification',
          title: '费用分类',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: costValue.classification,
        },
        {
          dataIndex: 'exchangecode',
          title: '交易市场',
          type: DATA_ENTRY.TRADINGMARKET,
          marketType: ['jys', 'yhj'],
          onChange: (e) => {
            if (e) {
              this.setState({
                exchangecode: e.value,
              });
            }
          },
        },
        {
          dataIndex: 'costtype',
          title: '费用类型',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: exchangecode == '113' ? costValue.costtype.yhjcosttype : exchangecode == '105' || exchangecode == '101' ? costValue.costtype.sjsAndsjscosttype : [],
        },
        {
          dataIndex: 'sectype',
          title: '证券类别',
          type: DATA_ENTRY.SELECT,
          allowClear: true,
          dataSource: costValue.costsectype,
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            classification: e.classification,
            groupid: e.groupid,
            productid: e.productid,
            portfolioid: e.portfolioid,
            exchangecode: e.exchangecode,
            costtype: e.costtype,
            sectype: e.sectype,
            currentPage: 1, //页码
            numInPage: 20, //每页条数
            reset: false,
          },
          () => {
            this.handleSearch();
          },
        );
      },
      onClear: () => {
        this.setState({
          classification: undefined,
          groupid: undefined,
          productid: undefined,
          portfolioid: undefined,
          exchangecode: undefined,
          costtype: undefined,
          sectype: undefined,
          reset: true,
        });
      },
    };

    return (
      <div>
        <AdvancedSearch {...searchProps}></AdvancedSearch>
      </div>
    );
  };

  //查询按钮触发事件
  handleSearch = () => {
    const { currentPage, numInPage, classification, groupid, productid, portfolioid, exchangecode, costtype, sectype, reset } = this.state;
    if (reset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    this.props.dispatch({
      type: 'costMaintainM/findAllCost',
      payload: {
        classification: classification,
        groupid: groupid,
        productid: productid,
        portfolioid: typeof portfolioid == 'string' ? portfolioid : undefined,
        exchangecode: exchangecode,
        costtype: costtype,
        sectype: sectype,
        currentPage: currentPage,
        numberPage: numInPage,
      },
      callback: (res) => {
        this.setState({
          columns: res.columns,
          dataSource: res.dataSource,
          total: res.pageInfo.total,
        });
      },
    });
  };

  //表格页码排序改变调用
  handleChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.handleSearch();
      },
    );
  };

  //新建
  addInfo = (refresh = false) => {
    this.setState(
      {
        itemInfo: {},
      },
      () => {
        this.changePage();
      },
    );
  };

  //切换表格/新建
  changePage = (refresh = false) => {
    this.setState({
      showEdit: !this.state.showEdit,
    });
    if (refresh) {
      this.handleSearch();
    }
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    let data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          key: 'action',
          dataIndex: 'action',
          title: '操作',
          type: 'action',
          fixed: 'right',
          render: (index, record) => {
            return <>{this.operateBtn(record)}</>;
          },
        });
      }
      data.map((item) => {
        if (item.key == 'classificationName') {
          item.fixed = 'left';
          item.width = '100px';
        }
        if (item.key == 'groupName') {
          item.fixed = 'left';
        }
        if (item.key == 'productName') {
          item.fixed = 'left';
        }
        if (item.key == 'portfolioName') {
          item.fixed = 'left';
        }
        if (item.key == 'exchangecode') {
          item.fixed = 'left';
          item.width = '130px';
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              let temp = config.filter((ele) => {
                return ele.value === text;
              });
              return temp[0].title;
            }
          };
        }

        if (item.key == 'sectypeiiName' || item.key == 'fundnatureName') {
          item.type = 'maxContent';
          item.width = '200px';
        }
        if (item.key == 'price' || item.key == 'maxMoney' || item.key == 'minMoney') {
          item.type = 'money';
        }
        if (item.key == 'pricemin' || item.key == 'pricemax') {
          item.type = 'money';
          item.toFixed = 4;
        }
        if (item.key == 'discountRatio') {
          item.align = 'right';
          item.title = '优惠比例(%)';
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              return (text * 100).toFixed(2);
            }
          };
        }
        if (item.key == 'calculationmethod') {
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              let temp = costValue.calculationmethod.filter((ele) => {
                return ele.value === text;
              });
              return temp && temp.length ? temp[0].title : '';
            }
          };
        }
        if (item.key == 'rate') {
          item.align = 'right';
          item.title = '比例(‰)';
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              return (text * 1000).toFixed(6);
            }
          };
        }
        if (item.key == 'istransaction') {
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else if (text == 0) {
              return '否';
            } else {
              return '是';
            }
          };
        }
      });
    }
    return data;
  };

  //列表关注下拉列表
  operateBtn = (record) => {
    const { tenantAdmin } = this.state;
    return (
      <Fragment>
        <Tooltip title='编辑'>
          <a disabled={record.classification == '1' || !tenantAdmin ? true : false} onClick={() => this.editData(record)}>
            编辑
          </a>
        </Tooltip>
        <Popconfirm
          disabled={record.classification == '1' || !tenantAdmin}
          icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
          title='是否要删除此行？'
          onConfirm={() => this.deleteData(record)}
        >
          <a disabled={record.classification == '1' || !tenantAdmin}>删除</a>
        </Popconfirm>
      </Fragment>
    );
  };

  // 编辑
  editData = (record) => {
    this.setState({
      showEdit: !this.state.showEdit,
      itemInfo: record,
    });
  };

  // 删除
  deleteData = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'costMaintainM/deleteCost',
      payload: { id: record.id },
      callback: () => {
        message.success('删除成功');
        this.handleSearch();
      },
    });
  };

  render() {
    const { showEdit, currentPage, numInPage, dataSource, columns, itemInfo, tenantAdmin, total, superMan } = this.state;
    const { loading } = this.props;
    const newColumns = this.changeColumns(columns);
    return (
      <ContentPackage
        title='费用维护'
        contentHtml={
          <div className={style.costMaintain}>
            <div style={{ display: showEdit ? 'none' : 'block' }}>
              {this.renderForm()}
              <div style={{ marginTop: '10px' }}>
                <PrimaryC title='新增' onClick={this.addInfo} disabled={!tenantAdmin || superMan} />
                <div style={{ marginTop: '10px' }}>
                  <TableC
                    columns={newColumns}
                    dataSource={dataSource || []}
                    loading={loading.effects['costMaintainM/findAllCost'] == true}
                    current={currentPage}
                    pageSize={numInPage}
                    total={total || 0}
                    scroll={{ x: 'max-content' }}
                    onChange={this.handleChange}
                    rowKey='id'
                  />
                </div>
              </div>
            </div>

            {showEdit ? <AddCost changeEdit={this.changePage} itemInfo={itemInfo} /> : ''}
          </div>
        }
      />
    );
  }
}
export default connect(({ costMaintainM, loading }) => ({
  costMaintainM,
  loading,
}))(CostMaintain);
